<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>时光胶囊 - 写给未来的自己</title>
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Expires" content="0">
    <style>
        /* 基础重置和全局样式 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            -webkit-tap-highlight-color: transparent;
        }

        html {
            font-size: 16px;
            -webkit-text-size-adjust: 100%;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'PingFang SC', 'Helvetica Neue', 'Microsoft YaHei', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 0;
            margin: 0;
            line-height: 1.6;
            overflow-x: hidden;
        }

        /* 登录容器 */
        .auth-container {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            padding: 30px 20px;
            border-radius: 20px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            max-width: 90%;
            width: 100%;
            margin: 20px auto;
            text-align: center;
            position: relative;
            min-height: 400px;
            display: flex;
            flex-direction: column;
            justify-content: center;
        }

        .auth-content {
            position: relative;
            z-index: 1;
        }

        .logo {
            width: 60px;
            height: 60px;
            background: linear-gradient(135deg, #ff99c8 0%, #ff99cc 100%);
            border-radius: 50%;
            margin: 0 auto 15px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            color: white;
            font-weight: bold;
        }

        .auth-title {
            color: #333;
            font-size: 1.5rem;
            margin-bottom: 8px;
            font-weight: 600;
        }

        .auth-subtitle {
            color: #666;
            font-size: 0.9rem;
            margin-bottom: 25px;
        }

        /* 输入框组 */
        .input-group {
            position: relative;
            margin-bottom: 20px;
        }

        .auth-input {
            width: 100%;
            padding: 15px;
            border: 2px solid #e1e5e9;
            border-radius: 12px;
            font-size: 16px;
            transition: all 0.3s ease;
            background: white;
            appearance: none;
            -webkit-appearance: none;
        }

        .auth-input:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .auth-input::placeholder {
            color: #aaa;
        }

        /* 按钮组 */
        .button-group {
            display: flex;
            flex-direction: column;
            gap: 12px;
            margin-top: 15px;
        }

        .auth-button {
            flex: 1;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 15px;
            border-radius: 12px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
            width: 100%;
            min-height: 50px;
        }

        .auth-button.secondary {
            background: linear-gradient(135deg, #ff99c8 0%, #ff99cc 100%);
        }

        .auth-button:hover {
            transform: translateY(-1px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.3);
        }

        .auth-button:active {
            transform: translateY(0);
        }

        .auth-button:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }

        .countdown {
            color: #666;
            font-size: 14px;
            margin-top: 15px;
            text-align: center;
        }

        /* 消息提示 */
        .message {
            padding: 12px 16px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-size: 14px;
            font-weight: 500;
        }

        .message.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .message.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        /* 主容器 */
        .container {
            width: 100%;
            min-height: 100vh;
            background: white;
            border-radius: 0;
            box-shadow: none;
            overflow: hidden;
            display: none;
        }

        /* 头部 */
        .main-header {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            z-index: 1001;
            background: linear-gradient(135deg, #ff99c8 0%, #ff99cc 100%);
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
            padding: 0;
        }

        .header-content {
            padding: 12px 20px 8px 20px;
        }

        .header-top {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 5px;
            width: 100%;
            gap: 20px;
        }

        .main-title {
            color: white;
            font-size: 1.0rem;
            font-weight: 600;
            margin: 0 0 5px 0;
            line-height: 1.3;
            text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
            text-align: left;
            flex: 1;
            min-width: 0;
        }

        .subtitle {
            color: rgba(255, 255, 255, 0.95);
            font-size: 0.9rem;
            margin: 0;
            line-height: 1.4;
            text-align: left;
            font-weight: 400;
            text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
        }

        .user-info {
            display: flex;
            flex-direction: column;
            align-items: flex-end;
            justify-content: flex-start;
            color: white;
            font-weight: 500;
            font-size: 0.9rem;
            flex-shrink: 0;
            text-align: right;
            min-width: fit-content;
            margin: 0;
        }

        .user-info span {
            font-size: 0.9rem;
            margin-bottom: 4px;
            white-space: nowrap;
            color: rgba(255, 255, 255, 0.95);
            font-weight: 400;
            text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
        }

        .logout-btn {
            background: transparent;
            color: rgba(255, 255, 255, 0.95);
            border: none;
            padding: 0;
            border-radius: 0;
            cursor: pointer;
            font-size: 0.9rem;
            transition: all 0.3s ease;
            min-height: auto;
            align-self: flex-end;
            white-space: nowrap;
            text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
            text-decoration: underline;
        }

        .logout-btn:hover {
            background: transparent;
            opacity: 0.8;
        }

        /* 标签栏 */
        .tabs-container {
            position: fixed;
            top: 90px;
            left: 0;
            right: 0;
            z-index: 1000;
            background: white;
            border-bottom: 1px solid #e8e8e8;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
        }

        .tabs {
            display: flex;
            justify-content: center;
            overflow-x: auto;
            -webkit-overflow-scrolling: touch;
            padding: 0 20px;
            scrollbar-width: none;
            margin: 0;
            background: white;
            border-top: 1px solid rgba(255, 255, 255, 0.2);
            border-bottom: 1px solid #e8e8e8;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
        }

        .tabs::-webkit-scrollbar {
            display: none;
        }

        .tab {
            padding: 12px 16px;
            cursor: pointer;
            font-weight: 500;
            color: #666;
            transition: all 0.3s ease;
            white-space: nowrap;
            flex-shrink: 0;
            font-size: 0.9rem;
            position: relative;
            border-bottom: 2px solid transparent;
            text-align: center;
        }

        .tab.active {
            color: #ff66b2;
            border-bottom-color: #ff66b2;
        }

        .tab:hover {
            color: #ff66b2;
            background-color: #f8f0f5;
        }

        /* 主要内容区域 */
        main {
            padding: 20px;
            padding-top: 140px;
        }

        /* 标签内容 */
        .content {
            display: none;
            animation: fadeIn 0.3s ease;
        }

        .content.active {
            display: block;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        /* 表单组 */
        .form-group {
            margin-bottom: 20px;
        }

        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: #333;
            font-size: 0.95rem;
        }

        input, textarea, select {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e1e5e9;
            border-radius: 10px;
            font-size: 16px;
            transition: border-color 0.3s ease;
            background: white;
            appearance: none;
            -webkit-appearance: none;
            max-width: 100%;
        }

        input:focus, textarea:focus, select:focus {
            outline: none;
            border-color: #ff99cc;
            box-shadow: 0 0 0 3px rgba(255, 153, 204, 0.1);
        }

        textarea {
            min-height: 120px;
            resize: vertical;
        }

        /* 创建按钮 */
        button[type="submit"] {
            background: linear-gradient(135deg, #ff99c8 0%, #ff99cc 100%);
            color: white;
            border: none;
            padding: 16px;
            border-radius: 10px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            width: 100%;
            min-height: 50px;
        }

        button[type="submit"]:hover {
            opacity: 0.9;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(255, 153, 204, 0.3);
        }

        button[type="submit"]:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        /* 胶囊列表 */
        .capsule-list {
            display: flex;
            flex-direction: column;
            gap: 15px;
            margin-top: 15px;
        }

        .capsule-card {
            background: linear-gradient(135deg, #fff0f5 0%, #ffe6f0 100%);
            border-radius: 12px;
            padding: 20px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
            border-left: 3px solid #ff99cc;
            transition: all 0.3s ease;
            position: relative;
        }

        .capsule-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.12);
        }

        .capsule-card-header {
            display: flex;
            flex-wrap: wrap;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 12px;
            gap: 8px;
        }

        .capsule-title {
            font-size: 1.1rem;
            font-weight: 600;
            color: #2c3e50;
            margin: 0;
            flex: 1;
            min-width: 0;
        }

        .capsule-content-wrapper {
            display: flex;
            flex-direction: column;
            gap: 15px;
            align-items: stretch;
        }

        .capsule-content {
            flex: 1;
            color: #34495e;
            line-height: 1.6;
            word-wrap: break-word;
            font-size: 0.95rem;
        }

        .capsule-image {
            width: 100%;
            height: 180px;
            object-fit: cover;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
        }

        .capsule-meta {
            font-size: 0.85rem;
            color: #7f8c8d;
            background: #f8f0f5;
            padding: 12px;
            border-radius: 8px;
            margin-top: 12px;
        }

        .capsule-status {
            font-size: 0.8rem;
            font-weight: 500;
            padding: 3px 8px;
            border-radius: 12px;
            margin-left: 8px;
            display: inline-block;
        }

        .status-unlocked {
            color: #28a745;
            background: #d4edda;
        }

        .status-locked {
            color: #ff6666;
            background: #ffe6e6;
        }

        .status-public {
            color: #007bff;
            background: #d1ecf1;
        }

        .status-private {
            color: #6c757d;
            background: #f8f9fa;
        }

        .lock-message {
            margin-top: 12px;
            padding: 10px;
            background: #fff0f5;
            border-radius: 6px;
            border: 1px solid #ffc2de;
            font-size: 0.85rem;
        }

        .loading {
            text-align: center;
            padding: 30px;
            color: #666;
        }

        .no-capsules {
            text-align: center;
            padding: 40px 20px;
            color: #666;
            font-style: italic;
        }

        .capsule-type-badge {
            background: #667eea;
            color: white;
            padding: 3px 8px;
            border-radius: 12px;
            font-size: 0.75rem;
            font-weight: 500;
        }

        .new-capsule-badge {
            background: #28a745;
            color: white;
            padding: 3px 8px;
            border-radius: 12px;
            font-size: 0.75rem;
            font-weight: 500;
            animation: blink 2s infinite;
        }

        @keyframes blink {
            0%, 50% { opacity: 1; }
            51%, 100% { opacity: 0.7; }
        }

        /* 可见性选项 */
        .visibility-options {
            display: flex;
            flex-direction: column;
            gap: 10px;
            margin-top: 10px;
        }

        .visibility-option {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 12px 15px;
            border: 2px solid #e9ecef;
            border-radius: 10px;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .visibility-option:hover {
            border-color: #ff99cc;
        }

        .visibility-option.selected {
            border-color: #ff66b2;
            background-color: #fff0f5;
        }

        .visibility-option input[type="radio"] {
            margin:0;
            width: 18px;
            height: 18px;
        }

        .visibility-option label {
            margin: 0;
            font-weight: normal;
            cursor: pointer;
            font-size: 0.95rem;
        }

        /* 小按钮组 */
        .button-group-small {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            margin-top: 15px;
        }

        .button-small {
            padding: 8px 12px;
            font-size: 0.85rem;
            border-radius: 8px;
            border: none;
            cursor: pointer;
            transition: all 0.3s ease;
            flex: 1;
            min-width: 80px;
            text-align: center;
        }

        .button-delete {
            background: #ff4757;
            color: white;
        }

        .button-public {
            background: #007bff;
            color: white;
        }

        .button-private {
            background: #6c757d;
            color: white;
        }

        .button-small:hover {
            opacity: 0.9;
            transform: translateY(-1px);
        }

        /* Toast通知 */
        .toast-container {
            position: fixed;
            top: 70px;
            left: 15px;
            right: 15px;
            z-index: 1000;
        }

        .toast {
            background: white;
            border-radius: 12px;
            padding: 16px;
            margin-bottom: 10px;
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
            display: flex;
            align-items: flex-start;
            animation: slideIn 0.3s ease;
            border-left: 4px solid #28a745;
        }

        .toast.error {
            border-left-color: #dc3545;
        }

        .toast.info {
            border-left-color: #17a2b8;
        }

        .toast.warning {
            border-left-color: #ffc107;
        }

        .toast-icon {
            font-size: 20px;
            margin-right: 12px;
            margin-top: 2px;
        }

        .toast-content {
            flex: 1;
        }

        .toast-title {
            font-weight: 600;
            margin-bottom: 4px;
            font-size: 0.5rem;
        }

        .toast-message {
            font-size: 0.9rem;
            color: #666;
        }

        .toast-close {
            background: none;
            border: none;
            font-size: 18px;
            cursor: pointer;
            color: #999;
            padding: 0;
            margin-left: 10px;
            width: 24px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        @keyframes slideIn {
            from {
                transform: translateX(100%);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }

        @keyframes slideOut {
            from {
                transform: translateX(0);
                opacity: 1;
            }
            to {
                transform: translateX(100%);
                opacity: 0;
            }
        }

        /* 测试模式提示 */
        .test-mode-banner {
            background: linear-gradient(135deg, #ffeb3b 0%, #ffc107 100%);
            color: #333;
            padding: 15px;
            border-radius: 10px;
            margin-bottom: 20px;
            text-align: center;
            border-left: 4px solid #ff9800;
            box-shadow: 0 4px 12px rgba(255, 193, 7, 0.3);
        }

        .test-mode-info {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }

        .test-mode-info span {
            font-weight: 600;
            font-size: 1rem;
        }

        .test-mode-info small {
            opacity: 0.9;
            font-size: 0.9rem;
            background: rgba(255, 255, 255, 0.5);
            padding: 4px 8px;
            border-radius: 4px;
            display: inline-block;
        }

        .quick-test-btn {
            background: linear-gradient(135deg, #4caf50 0%, #45a049 100%);
            color: white;
            border: none;
            padding: 10px 15px;
            border-radius: 8px;
            font-size: 0.9rem;
            cursor: pointer;
            margin-top: 10px;
            transition: all 0.3s ease;
            width: 100%;
        }

        /* 胶囊高亮动画 */
        @keyframes highlightPulse {
            0%, 100% {
                box-shadow: 0 0 0 rgba(40, 167, 69, 0.4);
                transform: scale(1);
            }
            50% {
                box-shadow: 0 0 20px rgba(40, 167, 69, 0.8);
                transform: scale(1.01);
            }
        }

        .capsule-card.highlight {
            animation: highlightPulse 2s ease-in-out;
            border: 2px solid #28a745;
            background: linear-gradient(135deg, #f0fff4 0%, #e6ffe6 100%);
        }

        /* 置顶胶囊样式 */
        .capsule-card.pinned {
            border: 2px solid #ffeb3b;
            background: linear-gradient(135deg, #fffde7 0%, #fff9c4 100%) !important;
        }

        .pinned-badge {
            background: #ffeb3b;
            color: #333;
            padding: 3px 8px;
            border-radius: 4px;
            font-size: 0.75rem;
            font-weight: 600;
        }

        /* 响应式设计 */
        @media (min-width: 768px) {
            .auth-container {
                max-width: 400px;
                padding: 40px;
                margin: 40px auto;
            }

            .logo {
                width: 80px;
                height: 80px;
                font-size: 32px;
            }

            .auth-title {
                font-size: 2rem;
            }

            .auth-subtitle {
                font-size: 1.1rem;
            }

            .container {
                max-width: 1200px;
                margin: 20px auto;
                border-radius: 15px;
                box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
                min-height: calc(100vh - 40px);
            }

            .header-content {
                padding: 12px 20px 8px 20px;
            }

            .main-title {
                font-size: 1.4rem;
            }

            .subtitle {
                font-size: 0.9rem;
            }

            .user-info {
                font-size: 0.9rem;
            }

            .user-info span {
                font-size: 0.9rem;
            }

            .tabs-container {
                top: 90px;
            }

            main {
                padding: 30px;
                padding-top: 140px;
            }

            .capsule-content-wrapper {
                flex-direction: row;
            }

            .capsule-image {
                width: 120px;
                height: 100px;
            }

            .visibility-options {
                flex-direction: row;
                gap: 15px;
            }

            .button-group {
                flex-direction: row;
                gap: 15px;
            }

            .auth-button {
                width: auto;
            }

            .toast-container {
                top: 20px;
                left: auto;
                right: 20px;
                max-width: 350px;
            }
        }

        @media (max-width: 768px) {
            .header-content {
                padding: 10px 15px 6px 15px;
            }

            .main-title {
                font-size: 1.2rem;
            }

            .subtitle {
                font-size: 0.85rem;
            }

            .user-info {
                font-size: 0.85rem;
                gap: 8px;
            }

            .tabs-container {
                top: 80px;
            }

            .tabs {
                padding: 0 15px;
            }

            .tab {
                padding: 10px 12px;
                font-size: 0.85rem;
            }

            main {
                padding-top: 120px;
                min-height: calc(100vh - 120px);
            }
        }

        @media (max-width: 480px) {
            .auth-container {
                padding: 25px 15px;
                margin: 15px;
            }

            .auth-title {
                font-size: 1.3rem;
            }

            .auth-subtitle {
                font-size: 0.85rem;
            }

            .auth-input {
                padding: 12px 15px;
                font-size: 16px;
            }

            .capsule-card {
                padding: 15px;
            }

            .capsule-title {
                font-size: 1rem;
            }

            .capsule-meta {
                font-size: 0.8rem;
                padding: 10px;
            }

            .capsule-status {
                font-size: 0.7rem;
                padding: 2px 6px;
            }

            .header-content {
                padding: 8px 12px 5px 12px;
            }

            .main-title {
                font-size: 1.1rem;
            }

            .subtitle {
                font-size: 0.8rem;
            }

            .user-info {
                font-size: 0.8rem;
                flex-direction: column;
                gap: 4px;
                align-items: flex-end;
            }

            .tabs-container {
                top: 75px;
            }

            main {
                padding-top: 110px;
                min-height: calc(100vh - 110px);
            }
        }

        @media (max-width: 360px) {
            .main-title {
                font-size: 1rem;
            }

            .subtitle {
                font-size: 0.75rem;
            }

            .user-info {
                font-size: 0.75rem;
            }

            .user-info span {
                font-size: 0.75rem;
            }

            .logout-btn {
                font-size: 0.7rem;
                padding: 2px 6px;
            }

            .tab {
                padding: 8px 10px;
                font-size: 0.75rem;
            }
        }

        /* 触摸目标优化 */
        .tab, .auth-button, button {
            min-height: 44px;
            min-width: 44px;
        }

 .header-content {
    padding: 12px 20px 8px 20px;
}

.header-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;   /* 间距适当不要太大 */
    margin-bottom: 2px; /* 两行之间几乎没有距离 */
}


.user-phone {
    color: white;
    font-weight: 500;
    font-size: 1rem;
    white-space: nowrap;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
    margin-left: 8px;
}

.subtitle {
    color: rgba(255, 255, 255, 0.95);
    font-size: 0.95rem;
    margin: 0;
    line-height: 1.4;
    text-align: left;
    font-weight: 400;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
    flex: 1;
    min-width: 0;
}

.logout-btn {
    background: transparent;
    color: rgba(255,255,255,0.93);
    border: none;
    font-size: 1rem;
    cursor: pointer;
    transition: opacity 0.18s;
    margin-left: 12px;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
    align-self: center;
    text-decoration: underline;
}
.logout-btn:hover {
    opacity: 0.7;
}

.header-content {
    padding: 12px 20px 0 20px; /* 下方去掉空白 */
}
.main-title {
    color: white;
    font-size: 1.1rem;
    font-weight: 600;
    margin: 0;
    line-height: 1.3;
    text-align: left;
    flex: 1;
    min-width: 0;
}

.tabs-container {
    margin-top: 0;
    padding-top: 0;
    top: 60px; /* 跟 header高度一致，可以微调，比如 header 如果有两行可以设 top: 68px 或 72px */
}

    </style>
</head>
<body>
<!-- Toast通知容器 -->
<div id="toast-container" class="toast-container"></div>

<!-- 登录容器 -->
<div id="auth-container" class="auth-container">
    <div class="auth-content">
        <div class="logo">⏱️</div>
        <h2 class="auth-title">时光胶囊</h2>
        <p class="auth-subtitle">写给未来的自己和朋友</p>

        <div id="auth-message"></div>

        <div id="login-form" class="auth-form">
            <div class="input-group">
                <input type="tel" id="phone-input" class="auth-input" placeholder="请输入手机号" maxlength="11" autocomplete="tel">
            </div>

            <div class="input-group">
                <input type="text" id="code-input" class="auth-input" placeholder="请输入验证码" maxlength="6" style="display: none;" autocomplete="off">
            </div>

            <div class="button-group">
                <button id="send-code-btn" class="auth-button">发送验证码</button>
                <button id="login-btn" class="auth-button secondary" style="display: none;">登录</button>
            </div>

            <div id="countdown" class="countdown" style="display: none;"></div>
        </div>
    </div>
</div>

<!-- 主内容容器 -->
<div id="main-container" class="container">

    <header class="main-header">
        <div class="header-content">
            <div class="header-row">
                <h1 class="main-title">风里已经有了温柔的味道</h1>
                <span id="user-phone" class="user-phone"></span>
            </div>
            <div class="header-row">
                <p class="subtitle">今天想写下什么？我在这里静静听着</p>
                <button class="logout-btn">退出</button>
            </div>
        </div>
        <!-- 标签栏 -->
        <div class="tabs-container">
            <div class="tabs">
                <div class="tab active" data-tab="create">创建胶囊</div>
                <div class="tab" data-tab="my-created">我创建的</div>
                <div class="tab" data-tab="my-received">我收到的</div>
                <div class="tab" data-tab="public">公开胶囊</div>
            </div>
        </div>
    </header>



    <main>
        <div id="create" class="content active">
            <div id="create-message"></div>

            <form id="create-form">
                <div class="form-group">
                    <label for="title">标题</label>
                    <input type="text" id="title" name="title" maxlength="50" placeholder="可选标题">
                </div>

                <div class="form-group">
                    <label for="content">内容 *</label>
                    <textarea id="content" name="content" required maxlength="1000"
                              placeholder="写下你想对未来的自己说的话..."></textarea>
                </div>

                <div class="form-group">
                    <label for="unlockTime">解锁时间 *</label>
                    <input type="datetime-local" id="unlockTime" name="unlockTime" required>
                </div>

                <div class="form-group">
                    <label for="image">图片（可选）</label>
                    <input type="file" id="image" name="image" accept="image/*">
                    <small style="color: #666; font-size: 0.85rem;">支持 JPG、PNG 格式，最大 10MB</small>
                </div>

                <div class="form-group">
                    <label for="recipientContact">接收人手机号（可选）</label>
                    <input type="text" id="recipientContact" name="recipientContact"
                           placeholder="输入手机号，可以邀请他人查看此胶囊">
                </div>

                <div class="form-group">
                    <label>可见性设置</label>
                    <div class="visibility-options">
                        <div class="visibility-option selected" data-visibility="private">
                            <input type="radio" id="isPrivate" name="isPublic" value="false" checked>
                            <label for="isPrivate">私有</label>
                        </div>
                        <div class="visibility-option" data-visibility="public">
                            <input type="radio" id="isPublic" name="isPublic" value="true">
                            <label for="isPublic">公开</label>
                        </div>
                    </div>
                    <small style="color: #666; font-size: 0.85rem;">
                        <span id="private-desc">私有：仅自己和接收人可见</span>
                        <span id="public-desc" style="display: none;">公开：解锁后所有人可见</span>
                    </small>
                </div>

                <button type="submit" id="create-button">创建时光胶囊</button>
            </form>
        </div>

        <div id="my-created" class="content">
            <div id="my-created-message"></div>
            <div class="form-group">
                <input type="text" id="search-created-input" placeholder="搜索我创建的胶囊..."
                       oninput="filterCapsules('my-created')">
            </div>
            <div id="my-created-loading" class="loading">加载中...</div>
            <div id="no-my-created-capsules" class="no-capsules" style="display: none;">
                您还没有创建任何时光胶囊
            </div>
            <div id="my-created-list" class="capsule-list"></div>
        </div>

        <div id="my-received" class="content">
            <div id="my-received-message"></div>
            <div class="form-group">
                <input type="text" id="search-received-input" placeholder="搜索我收到的胶囊..."
                       oninput="filterCapsules('my-received')">
            </div>
            <div id="my-received-loading" class="loading">加载中...</div>
            <div id="no-my-received-capsules" class="no-capsules" style="display: none;">
                您还没有收到任何时光胶囊
            </div>
            <div id="my-received-list" class="capsule-list"></div>
        </div>

        <div id="public" class="content">
            <div id="public-message"></div>
            <div class="form-group">
                <input type="text" id="search-public-input" placeholder="搜索公开胶囊..."
                       oninput="filterCapsules('public')">
            </div>
            <div id="public-loading" class="loading">加载中...</div>
            <div id="no-public-capsules" class="no-capsules" style="display: none;">
                暂时没有公开的时光胶囊
            </div>
            <div id="public-list" class="capsule-list"></div>
        </div>
    </main>
</div>

<script>
// 保持原有的JavaScript逻辑不变，只添加事件监听器的优化
document.addEventListener('DOMContentLoaded', function() {
    console.log('页面加载完成');

    // 添加事件监听器 - 修复按钮点击问题
    document.getElementById('send-code-btn').addEventListener('click', sendVerificationCode);
    document.getElementById('login-btn').addEventListener('click', login);
    document.querySelector('.logout-btn').addEventListener('click', logout);
    // 优化标签页切换
document.querySelectorAll('.tab').forEach(tab => {
    tab.addEventListener('click', function(e) {
        e.preventDefault();
        const tabName = this.getAttribute('data-tab');
        switchTab(tabName); // 修复：改为正确的函数调用
    });
});

    // 优化可见性选择
    document.querySelectorAll('.visibility-option').forEach(option => {
        option.addEventListener('click', function() {
            const type = this.getAttribute('data-visibility');
            selectVisibility(type);
        });
    });

    // 优化退出按钮
    document.querySelector('.logout-btn').addEventListener('click', logout);

    // 保持原有逻辑...
    checkAuthStatus();
    checkTestMode();
    checkUrlParams();
    setDefaultUnlockTime();
});

// 其余JavaScript代码保持不变...
console.log("时光胶囊前端应用已启动");

// API基础地址
const API_BASE = 'https://expensive-monroe-moms-revenues.trycloudflare.com/api';

// 全局变量
let authToken = localStorage.getItem('authToken');
let currentPhone = localStorage.getItem('userPhone');
let countdownTimer = null;
let isTestMode = false;
let newlyAcceptedCapsules = new Set();

// Toast通知系统
class Toast {
    static show(title, message, type = 'success', duration = 5000) {
        const toastContainer = document.getElementById('toast-container');
        const toast = document.createElement('div');
        toast.className = `toast ${type}`;

        const icons = {
            success: '✅',
            error: '❌',
            warning: '⚠️',
            info: 'ℹ️'
        };

        toast.innerHTML = `
            <span class="toast-icon">${icons[type]}</span>
            <div class="toast-content">
                <div class="toast-title">${title}</div>
                <div class="toast-message">${message}</div>
            </div>
            <button class="toast-close" onclick="this.parentElement.remove()">×</button>
        `;

        toastContainer.appendChild(toast);

        if (duration > 0) {
            setTimeout(() => {
                if (toast.parentElement) {
                    toast.style.animation = 'slideOut 0.3s ease';
                    setTimeout(() => toast.remove(), 300);
                }
            }, duration);
        }

        return toast;
    }
}

// 设置默认解锁时间函数（修复版）
function setDefaultUnlockTime() {
    try {
        const now = new Date();
        const oneMinuteLater = new Date(now.getTime() + 120000); // 2分钟后

        const formattedTime = formatDateTimeLocal(oneMinuteLater);
        const unlockTimeInput = document.getElementById('unlockTime');

        if (unlockTimeInput) {
            unlockTimeInput.value = formattedTime;
            console.log('默认解锁时间设置为:', formattedTime);
        } else {
            console.warn('未找到unlockTime元素');
        }
    } catch (error) {
        console.error('设置默认解锁时间失败:', error);
    }
}

// 格式化为 datetime-local 格式
function formatDateTimeLocal(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');

    return `${year}-${month}-${day}T${hours}:${minutes}`;
}

// 可见性选择函数
function selectVisibility(type) {
    const privateOption = document.querySelector('.visibility-option[data-visibility="private"]');
    const publicOption = document.querySelector('.visibility-option[data-visibility="public"]');
    const privateDesc = document.getElementById('private-desc');
    const publicDesc = document.getElementById('public-desc');

    if (type === 'private') {
        privateOption.classList.add('selected');
        publicOption.classList.remove('selected');
        document.getElementById('isPrivate').checked = true;
        privateDesc.style.display = 'inline';
        publicDesc.style.display = 'none';
    } else {
        privateOption.classList.remove('selected');
        publicOption.classList.add('selected');
        document.getElementById('isPublic').checked = true;
        privateDesc.style.display = 'none';
        publicDesc.style.display = 'inline';
    }
}

// 检查认证状态
function checkAuthStatus() {
    if (authToken && currentPhone) {
        showMainContent();
        checkPendingInvitation();
    } else {
        showAuthForm();
    }
}

// 显示登录表单
function showAuthForm() {
    document.getElementById('auth-container').style.display = 'block';
    document.getElementById('main-container').style.display = 'none';
}

// 登录 - 修复版本（修正语法错误）
async function login() {
    const phone = document.getElementById('phone-input').value.trim();
    const code = document.getElementById('code-input').value.trim();

    if (!isValidPhone(phone)) {
        showAuthMessage('请输入正确的手机号', 'error');
        return;
    }

    if (!code) {
        showAuthMessage('请输入验证码', 'error');
        return;
    }

    const loginBtn = document.getElementById('login-btn');
    const originalText = loginBtn.textContent;
    loginBtn.disabled = true;
    loginBtn.textContent = '登录中...';

    try {
        const response = await fetch(`${API_BASE}/auth/login?phone=${encodeURIComponent(phone)}&code=${encodeURIComponent(code)}`, {
            method: 'POST'
        });

        const result = await response.json();

        if (result.success && result.token) {
            authToken = result.token;
            currentPhone = phone;
            localStorage.setItem('authToken', authToken);
            localStorage.setItem('userPhone', currentPhone);

            Toast.show('登录成功', '正在处理...', 'success');
            showMainContent();

            const pendingInvitation = localStorage.getItem('pendingInvitation');
            const intendedRecipient = localStorage.getItem('intendedRecipient');

            if (pendingInvitation) {
                if (intendedRecipient === phone) {
                    console.log('开始处理待定邀请:', pendingInvitation);
                    handlePendingInvitation(pendingInvitation);
                    switchTab('my-received');
                } else {
                    Toast.show('账号不匹配', `此邀请是发给 ${intendedRecipient} 的`, 'warning');
                    localStorage.removeItem('pendingInvitation');
                    localStorage.removeItem('intendedRecipient');
                    loadCapsules('my-created');
                }
            } else {
                loadCapsules('my-created');
            }

        } else {
            showAuthMessage(result.message || '登录失败', 'error');
            loginBtn.disabled = false;
            loginBtn.textContent = originalText;
        }
    } catch (error) {
        showAuthMessage('网络错误，请重试', 'error');
        loginBtn.disabled = false;
        loginBtn.textContent = originalText;
    }
}


// 处理待定邀请（后台处理）
async function handlePendingInvitation(token) {
    try {
        console.log('处理邀请令牌:', token);

        const response = await fetch(`${API_BASE}/invitations/accept`, {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${authToken}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ token: token })
        });

        if (response.ok) {
            const result = await response.json();
            if (result.success) {


                if (result.capsuleId) {
                    newlyAcceptedCapsules.add(result.capsuleId);

                    setTimeout(() => {
                        loadCapsules('my-received');

                        setTimeout(() => {
                            const capsuleElement = document.getElementById(`capsule-${result.capsuleId}`);
                            if (capsuleElement) {
                                capsuleElement.classList.add('highlight');
                                capsuleElement.scrollIntoView({ behavior: 'smooth', block: 'center' });

                                if (!document.querySelector('.tab[data-tab="my-received"]').classList.contains('active')) {
                                    switchTab('my-received');
                                }
                            }
                        }, 500);
                    }, 1000);
                }
            } else {
                Toast.show('邀请处理失败', result.message || '请稍后重试', 'error');
            }
        } else {
            Toast.show('邀请处理失败', '服务器错误，请稍后重试', 'error');
        }
    } catch (error) {
        console.error('处理邀请时出错:', error);
        Toast.show('网络错误', '邀请处理失败，请检查网络连接', 'error');
    } finally {
        localStorage.removeItem('pendingInvitation');
        localStorage.removeItem('intendedRecipient');
    }
}

// 切换标签页
function switchTab(tabName) {
    console.log('切换标签页到:', tabName);

    document.querySelectorAll('.tab').forEach(tab => {
        tab.classList.remove('active');
    });

    document.querySelectorAll('.content').forEach(content => {
        content.classList.remove('active');
    });

    const targetTab = document.querySelector(`.tab[data-tab="${tabName}"]`);
    if (targetTab) {
        targetTab.classList.add('active');
    }

    const targetContent = document.getElementById(tabName);
    if (targetContent) {
        targetContent.classList.add('active');
    }

    if (tabName === 'create') {
        setTimeout(setDefaultUnlockTime, 50);
    }

    if (tabName !== 'create') {
        loadCapsules(tabName);
    }
}

// 显示主内容
function showMainContent() {
    console.log('显示主内容界面');
    document.getElementById('auth-container').style.display = 'none';
    document.getElementById('main-container').style.display = 'block';
    document.getElementById('user-phone').textContent = currentPhone;
}

// 检查测试模式
async function checkTestMode() {
    try {
        const response = await fetch('/api/config/test-mode');
        const result = await response.json();
        isTestMode = result.testModeEnabled;

        if (isTestMode) {
            const authMessage = document.getElementById('auth-message');
            authMessage.innerHTML = `
                <div class="test-mode-banner">
                    <div class="test-mode-info">
                        <span>🔧 测试模式已启用</span>
                        <small>验证码: ${result.testCode || '123456'}</small>
                    </div>
                    <button class="quick-test-btn" onclick="fillTestCredentials()">
                        快速测试
                    </button>
                </div>
            `;
        }
    } catch (error) {
        console.log('无法获取测试模式状态，默认启用测试模式');
        isTestMode = true;
    }
}

// 填充测试凭证
function fillTestCredentials() {
    document.getElementById('phone-input').value = '13271267723';
    document.getElementById('code-input').value = '123456';
    document.getElementById('code-input').style.display = 'block';
    document.getElementById('login-btn').style.display = 'block';
}

// 发送验证码
async function sendVerificationCode() {
    const phone = document.getElementById('phone-input').value.trim();

    if (!isValidPhone(phone)) {
        showAuthMessage('请输入正确的手机号', 'error');
        return;
    }

    const sendBtn = document.getElementById('send-code-btn');
    sendBtn.disabled = true;
    sendBtn.textContent = '发送中...';

    try {
        const response = await fetch(`${API_BASE}/auth/send-code?phone=${encodeURIComponent(phone)}`, {
            method: 'POST'
        });

        const result = await response.json();

        if (result.success) {
            showAuthMessage('验证码发送成功', 'success');
            document.getElementById('code-input').style.display = 'block';
            document.getElementById('login-btn').style.display = 'block';
            startCountdown(60);
        } else {
            showAuthMessage(result.message || '发送失败', 'error');
            sendBtn.disabled = false;
            sendBtn.textContent = '发送验证码';
        }
    } catch (error) {
        showAuthMessage('网络错误，请重试', 'error');
        sendBtn.disabled = false;
        sendBtn.textContent = '发送验证码';
    }
}

// 开始倒计时
function startCountdown(seconds) {
    const countdownEl = document.getElementById('countdown');
    const sendBtn = document.getElementById('send-code-btn');

    countdownEl.style.display = 'block';
    sendBtn.disabled = true;

    let remaining = seconds;
    updateCountdown();

    countdownTimer = setInterval(() => {
        remaining--;
        if (remaining <= 0) {
            clearInterval(countdownTimer);
            sendBtn.disabled = false;
            sendBtn.textContent = '重新发送';
            countdownEl.style.display = 'none';
        } else {
            updateCountdown();
        }
    }, 1000);

    function updateCountdown() {
        countdownEl.textContent = `${remaining}秒后可重新发送`;
        sendBtn.textContent = `重新发送(${remaining}s)`;
    }
}

function logout() {
    authToken = null;
    currentPhone = null;
    localStorage.removeItem('authToken');
    localStorage.removeItem('userPhone');
    localStorage.removeItem('pendingInvitation');
    localStorage.removeItem('intendedRecipient');
    localStorage.removeItem('invitationToken');

    if (countdownTimer) {
        clearInterval(countdownTimer);
        countdownTimer = null;
    }

    document.getElementById('toast-container').innerHTML = '';
    document.getElementById('auth-message').innerHTML = '';
    resetLoginForm();
    showAuthForm();
}

function resetLoginForm() {
    document.getElementById('phone-input').value = '';
    document.getElementById('code-input').value = '';
    document.getElementById('code-input').style.display = 'none';
    document.getElementById('login-btn').textContent = '登录';
    document.getElementById('login-btn').disabled = false;
    document.getElementById('login-btn').style.display = 'none';
    document.getElementById('send-code-btn').disabled = false;
    document.getElementById('send-code-btn').textContent = '发送验证码';
    document.getElementById('countdown').style.display = 'none';
}

function showAuthMessage(message, type) {
    const messageEl = document.getElementById('auth-message');
    messageEl.innerHTML = `<div class="message ${type}">${message}</div>`;
    setTimeout(() => {
        messageEl.innerHTML = '';
    }, 3000);
}

function isValidPhone(phone) {
    return /^1[3-9]\d{9}$/.test(phone);
}

function checkUrlParams() {
    const urlParams = new URLSearchParams(window.location.search);
    const token = urlParams.get('token');
    const invitationToken = urlParams.get('invitation');

    if (token) {
        console.log('检测到邀请令牌:', token);
        handleInvitationToken(token);
    }

    if (invitationToken) {
        console.log('检测到重定向邀请:', invitationToken);
        handleInvitationToken(invitationToken);
        window.history.replaceState({}, document.title, window.location.pathname);
    }
}

function handleInvitationToken(token) {
    fetch(`${API_BASE}/invitations/invitation-info?token=${token}`)
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                const intendedRecipient = result.intendedRecipient;
                const currentUser = localStorage.getItem('userPhone');

                if (currentUser && currentUser === intendedRecipient) {
                    handleInvitationFromUrl(token);
                } else if (currentUser && currentUser !== intendedRecipient) {
                    showAccountSwitchPrompt(intendedRecipient, token);
                } else {
                    showLoginPrompt(intendedRecipient, token);
                }
            }
        })
        .catch(error => {
            console.error('获取邀请信息失败:', error);
            Toast.show('错误', '邀请链接无效或已过期', 'error');
        });
}

function showAccountSwitchPrompt(intendedRecipient, token) {
    const authMessage = document.getElementById('auth-message');
    authMessage.innerHTML = `
        <div class="message warning">
            <h4>📨 邀请接收提示</h4>
            <p>此时光胶囊邀请是发给 <strong>${intendedRecipient}</strong> 的</p>
            <p>当前登录账号: <strong>${localStorage.getItem('userPhone')}</strong></p>
            <div style="margin-top: 15px;">
                <button class="auth-button" onclick="logoutAndPrepareForInvitation('${intendedRecipient}', '${token}')">
                    🔄 切换到 ${intendedRecipient}
                </button>
                <button class="auth-button secondary" onclick="ignoreInvitation()" style="margin-left: 10px; margin-top: 10px;">
                    ❌ 忽略邀请
                </button>
            </div>
        </div>
    `;
}

function logoutAndPrepareForInvitation(intendedRecipient, token) {
    localStorage.setItem('pendingInvitation', token);
    localStorage.setItem('intendedRecipient', intendedRecipient);
    logout();
}

function showLoginPrompt(intendedRecipient, token) {
    const authMessage = document.getElementById('auth-message');
    authMessage.innerHTML = `
        <div class="message info">
            <h4>📨 您有一个时光胶囊邀请</h4>
            <p>邀请接收人: <strong>${intendedRecipient}</strong></p>
            <p>请使用手机号 ${intendedRecipient} 登录以接受邀请</p>
        </div>
    `;

    document.getElementById('phone-input').value = intendedRecipient;
    localStorage.setItem('pendingInvitation', token);
}

async function handleInvitationFromUrl(token) {
    try {
        const response = await fetch(`${API_BASE}/invitations/accept`, {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${authToken}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ token: token })
        });

        if (response.ok) {
            const result = await response.json();
            if (result.success) {


                if (result.capsuleId) {
                    newlyAcceptedCapsules.add(result.capsuleId);
                }

                switchTab('my-received');

            } else {
                Toast.show('接受失败', result.message || '邀请处理失败', 'error');
            }
        } else if (response.status === 403) {
            Toast.show('权限不足', '您没有权限接受此邀请', 'error');
        } else if (response.status === 401) {
            Toast.show('登录已过期', '请重新登录', 'error');
            logout();
        } else {
            Toast.show('请求失败', '请重试', 'error');
        }
    } catch (error) {
        console.error('处理邀请失败:', error);
        Toast.show('网络错误', '请检查网络连接', 'error');
    }
}

function checkPendingInvitation() {
    const invitationToken = localStorage.getItem('invitationToken');
    console.log('检查待处理邀请:', invitationToken);

    if (invitationToken) {
        if (authToken) {
            acceptPendingInvitation(invitationToken);
        }
    }
}

async function acceptPendingInvitation(token) {
    try {
        const response = await fetch(`${API_BASE}/invitations/accept`, {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${authToken}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ token: token })
        });

        if (response.ok) {
            const result = await response.json();
            if (result.success) {

                if (result.capsuleId) {
                    newlyAcceptedCapsules.add(result.capsuleId);
                }

                localStorage.removeItem('invitationToken');
                loadCapsules('my-received');
            }
        }
    } catch (error) {
        console.error('处理待定邀请失败:', error);
    }
}

async function loadCapsules(tabName) {
    console.log('加载胶囊列表:', tabName);
    const loading = document.getElementById(`${tabName}-loading`);
    const list = document.getElementById(`${tabName}-list`);
    const noCapsules = document.getElementById(`no-${tabName}-capsules`);
    const messageEl = document.getElementById(`${tabName}-message`);

    loading.style.display = 'block';
    list.innerHTML = '';
    noCapsules.style.display = 'none';
    messageEl.innerHTML = '';

    try {
        let url;
        switch(tabName) {
            case 'my-created':
                url = `${API_BASE}/capsules/my-created`;
                break;
            case 'my-received':
                url = `${API_BASE}/capsules/my-received`;
                break;
            case 'public':
                url = `${API_BASE}/capsules/public`;
                break;
            default:
                url = `${API_BASE}/capsules`;
        }

        const response = await fetch(url, {
            headers: {
                'Authorization': `Bearer ${authToken}`,
                'Content-Type': 'application/json'
            }
        });

        if (response.ok) {
            const capsules = await response.json();
            console.log(`获取到${tabName}胶囊数据:`, capsules.length);
            renderCapsules(capsules, tabName);
        } else if (response.status === 401) {
            Toast.show('登录已过期', '请重新登录', 'error');
            logout();
        } else {
            console.log('加载失败，状态码:', response.status);
            messageEl.innerHTML = `<div class="message error">加载失败，请重试</div>`;
        }
    } catch (error) {
        console.log('加载错误:', error);
        messageEl.innerHTML = `<div class="message error">网络错误: ${error.message}</div>`;
    } finally {
        loading.style.display = 'none';
    }
}

function renderCapsules(capsules, tabName) {
    const list = document.getElementById(`${tabName}-list`);
    const loading = document.getElementById(`${tabName}-loading`);
    const noCapsules = document.getElementById(`no-${tabName}-capsules`);

    list.innerHTML = '';
    loading.style.display = 'none';

    if (capsules.length === 0) {
        noCapsules.style.display = 'block';
        return;
    }

    noCapsules.style.display = 'none';

    const pinnedCapsules = [];
    const normalCapsules = [];

    capsules.forEach(capsule => {
        if (newlyAcceptedCapsules.has(capsule.id)) {
            pinnedCapsules.push(capsule);
        } else {
            normalCapsules.push(capsule);
        }
    });

    pinnedCapsules.forEach(capsule => {
        const card = createCapsuleCard(capsule, tabName, true);
        list.appendChild(card);

        setTimeout(() => {
            card.classList.add('highlight');
        }, 100);
    });

    normalCapsules.forEach(capsule => {
        const card = createCapsuleCard(capsule, tabName);
        list.appendChild(card);
    });

    if (pinnedCapsules.length > 0) {
        setTimeout(() => {
            const firstPinnedCard = document.getElementById(`capsule-${pinnedCapsules[0].id}`);
            if (firstPinnedCard) {
                firstPinnedCard.scrollIntoView({ behavior: 'smooth', block: 'center' });
            }
        }, 200);
    }
}

function createCapsuleCard(capsule, tabName, isPinned = false) {
    const card = document.createElement('div');
    card.className = 'capsule-card';
    if (isPinned) {
        card.classList.add('pinned');
    }
    card.id = `capsule-${capsule.id}`;
    card.dataset.title = capsule.title ? capsule.title.toLowerCase() : '';
    card.dataset.content = capsule.content ? capsule.content.toLowerCase() : '';

    if (!capsule.unlocked) {
        card.style.background = 'linear-gradient(135deg, #fff0f5 0%, #ffe6f0 100%)';
    } else {
        card.style.background = 'linear-gradient(135deg, #f0f8ff 0%, #e6f2ff 100%)';
    }

    let imageHtml = '';
    if (capsule.imageUrl) {
        imageHtml = `<img src="${capsule.imageUrl}" alt="胶囊图片" class="capsule-image" onerror="this.style.display='none'">`;
    }

    const statusClass = capsule.unlocked ? 'status-unlocked' : 'status-locked';
    const statusText = capsule.unlocked ? '✅ 已解锁' : '⏳ 未解锁';

    const isPublic = (capsule.isPublic === true || capsule.isPublic === 1) || (capsule.public === true || capsule.public === 1);
    const visibilityClass = isPublic ? 'status-public' : 'status-private';
    const visibilityText = isPublic ? '🌐 公开' : '🔒 私有';

    const timeInfo = capsule.unlocked ?
        `解锁于: ${new Date(capsule.unlockTime).toLocaleString('zh-CN')}` :
        `将于: ${new Date(capsule.unlockTime).toLocaleString('zh-CN')} 解锁`;

    let typeBadge = '';
    if (tabName === 'my-re' && capsule.senderPhone) {
        typeBadge = `<span class="capsule-type-badge">来自: ${capsule.senderPhone}</span>`;
    }

    let newBadge = '';
    if (newlyAcceptedCapsules.has(capsule.id)) {
        newBadge = `<span class="new-capsule-badge">新接受</span>`;
    }

    card.innerHTML = `
        <div class="capsule-card-header">
            <div class="capsule-title">${capsule.title || '无标题'}</div>
            ${typeBadge}
            ${newBadge}
        </div>
        <div class="capsule-content-wrapper">
            <div class="capsule-content">${capsule.content || '无内容'}</div>
            ${imageHtml ? imageHtml : ''}
        </div>
        <div class="capsule-meta">
            📅 创建时间: ${new Date(capsule.createdAt).toLocaleString('zh-CN')}
            <span class="capsule-status ${statusClass}">${statusText}</span>
            <span class="capsule-status ${visibilityClass}">${visibilityText}</span><br>
            ⏰ ${timeInfo}
        </div>
        ${!capsule.unlocked ?
            `<div class="lock-message">
                <small>⏳ 此胶囊还未到解锁时间，无法查看完整内容</small>
            </div>` : ''
        }
        ${tabName === 'my-created' ?
            `<div class="button-group-small">
                <button class="button-small button-delete" onclick="deleteCapsule(${capsule.id}, '${tabName}')">
                    删除
                </button>
                ${capsule.isPublic ?
                    `<button class="button-small button-private" onclick="updateCapsuleVisibility(${capsule.id}, false)">
                        设为私有
                    </button>` :
                    `<button class="button-small button-public" onclick="updateCapsuleVisibility(${capsule.id}, true)">
                        设为公开
                    </button>`
                }
            </div>` : ''
        }
    `;

    return card;
}

function filterCapsules(tabName) {
    const searchTerm = document.getElementById(`search-${tabName}-input`).value.toLowerCase();
    const capsules = document.querySelectorAll(`#${tabName}-list .capsule-card`);

    capsules.forEach(capsule => {
        const title = capsule.dataset.title || '';
        const content = capsule.dataset.content || '';

        if (title.includes(searchTerm) || content.includes(searchTerm)) {
            capsule.style.display = 'block';
        } else {
            capsule.style.display = 'none';
        }
    });
}

async function deleteCapsule(id, tabName) {
    if (!confirm('确定要删除这个时光胶囊吗？此操作不可恢复。')) {
        return;
    }

    try {
        const response = await fetch(`${API_BASE}/capsules/${id}`, {
            method: 'DELETE',
            headers: {
                'Authorization': `Bearer ${authToken}`,
                'Content-Type': 'application/json'
            }
        });

        if (response.ok) {
            loadCapsules(tabName);
        } else {
            Toast.show('删除失败', '请重试', 'error');
        }
    } catch (error) {
        console.log('失败:', error);
        Toast.show('删除失败', '网络错误，请重试', 'error');
    }
}

async function updateCapsuleVisibility(capsuleId, isPublic) {
    const action = isPublic ? '设为公开' : '设为私有';
    if (!confirm(`确定要将此胶囊${action}吗？`)) {
        return;
    }

    try {
        const response = await fetch(`${API_BASE}/capsules/${capsuleId}/visibility?isPublic=${isPublic}`, {
            method: 'PATCH',
            headers: {
                'Authorization': `Bearer ${authToken}`,
                'Content-Type': 'application/json'
            }
        });

        if (response.ok) {
            loadCapsules('my-created');
        } else {
            Toast.show(`${action}失败`, '请重试', 'error');
        }
    } catch (error) {
        console.log('更新可见性失败:', error);
        Toast.show('更新失败', '网络错误，请重试', 'error');
    }
}

document.getElementById('create-form').addEventListener('submit', async function(e) {
    e.preventDefault();

    const createButton = document.getElementById('create-button');
    const originalText = createButton.textContent;

    createButton.textContent = '创建中...';
    createButton.disabled = true;

    try {
        const formData = new FormData();
        formData.append('title', document.getElementById('title').value);
        formData.append('content', document.getElementById('content').value);
        formData.append('unlockTime', document.getElementById('unlockTime').value);

        const isPublic = document.querySelector('input[name="isPublic"]:checked').value;
        formData.append('isPublic', isPublic);

        const imageFile = document.getElementById('image').files[0];
        if (imageFile) {
            formData.append('imageFile', imageFile);
        }

        const recipientContact = document.getElementById('recipientContact').value;
        if (recipientContact) {
            formData.append('recipientContact', recipientContact);
        }

        console.log('发送创建请求到:', `${API_BASE}/capsules`);
        const response = await fetch(`${API_BASE}/capsules`, {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${authToken}`
            },
            body: formData
        });

        console.log('服务器响应状态:', response.status);

        if (response.ok) {
            const result = await response.json();
            console.log('胶囊创建成功:', result);

            document.getElementById('create-form').reset();
            setDefaultUnlockTime();
            selectVisibility('private');

            setTimeout(function() {
                console.log('自动跳转到我创建的页面');
                switchTab('my-created');
            }, 1500);
        } else {
            const errorText = await response.text();
            console.log('创建失败:', errorText);
            Toast.show('创建失败', errorText, 'error');
        }
    } catch (error) {
        console.log('网络错误:', error);
        Toast.show('创建失败', '网络错误: ' + error.message, 'error');
    } finally {
        createButton.textContent = originalText;
        createButton.disabled = false;
    }
});

async function acceptInvitation(token) {
    try {
        const response = await fetch(`${API_BASE}/invitations/accept`, {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${authToken}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ token: token })
        });

        if (response.ok) {
            const result = await response.json();
            if (result.success) {

                if (result.capsuleId) {
                    newlyAcceptedCapsules.add(result.capsuleId);
                }

                await loadCapsules('my-received');

                if (result.capsuleId) {
                    setTimeout(() => {
                        const capsuleElement = document.getElementById(`capsule-${result.capsuleId}`);
                        if (capsuleElement) {
                            capsuleElement.classList.add('highlight');
                            capsuleElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
                        }
                    }, 500);
                }

                return true;
            } else {
                Toast.show('接受失败', result.message || '邀请处理失败', 'error');
                return false;
            }
        } if (response.status === 403) {
            Toast.show('权限不足', '您没有权限接受此邀请', 'error');
            return false;
        } else if (response.status === 401) {
            Toast.show('登录已过期', '请重新', 'error');
            logout();
            return false;
        } else {
            Toast.show('请求失败', '请重试', 'error');
            return false;
        }
    } catch (error) {
        console.error('接受邀请失败:', error);
        Toast.show('网络错误', '请检查网络连接', 'error');
        return false;
    }
}
</script>
</body>
</html>